import { ref } from 'vue';

function useSearchHistory(name, max = 20) {
	
	const searchHistory = ref();
	
	function reset() {
		searchHistory.value = JSON.parse(localStorage.getItem(name) || '[]');
	}
	
	function add(value) {
		searchHistory.value = [...new Set([value, ...searchHistory.value])];
		if (searchHistory.value.length > 10) searchHistory.value.length = 10;
		localStorage.setItem(name, JSON.stringify(searchHistory.value));
	}
	
	function remove(value) {
		searchHistory.value = searchHistory.value.filter(his => his != value);
		localStorage.setItem(name, JSON.stringify(searchHistory.value));
	}
	
	function clear() {
		localStorage.removeItem(name);
		searchHistory.value = [];
	}
	
	reset();
	
	return {
		searchHistory,
		reset, add, remove, clear
	}
	
}

export default useSearchHistory;